package com.macro.ai.alibaba.controller;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName AlibabaController
 * @Description TODO
 * @Author wanghong
 * @Date 2025/6/21 14:05
 * @Version 1.0
 **/
@RestController
public class AlibabaController {

    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手，请根据用户提问回答！";

    @Autowired
    private final ChatClient dashScopeChatModel;

    public AlibabaController(ChatClient.Builder chatClientBuilder){

        this.dashScopeChatModel = chatClientBuilder
                .defaultSystem(DEFAULT_PROMPT)
                //实现chat memory的advisor
                //在使用Chat memory时，需要指定对话ID，以便Spring AI处理上下文。
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(new InMemoryChatMemory())
                )
                //实现Logger的Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                //设置ChatClient中ChatModel的options参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withTopP(0.7)
                                .build()
                )
                .build();
    }

    @GetMapping("/simple/chat")
    public String simpleChat(String query) {
        return dashScopeChatModel.prompt(query).call().content();
    }

    /**
     * Stream 流式调用。可以使大模型的输出信息实现打字机效果。
     * @return Flux<String> types.
     */
//    @GetMapping("/stream/chat")
//    public Flux<String> streamChat(HttpServletResponse response) {
//
//        // 避免返回乱码
//        response.setCharacterEncoding("UTF-8");
//
//        Flux<ChatResponse> stream = dashScopeChatModel.stream(new Prompt(DEFAULT_PROMPT));
//        return stream.map(resp -> resp.getResult().getOutput().getContent());
//    }
}
